

function resetTextForm() {
    $('#text-modal-title').html('Text Input');
    $('#text-save-btn').html('Create Text Input');
    
    $('#text-type').val('text');
    $('#text-guideline').val('none');
    
    $('#text-input-form').find('.number-control').slideUp();
    $('#text-input-form').find('.guideline-control').slideUp();
    $('#text-input-form').find('.password-control').slideUp();
    
    $('#text-db-type').find('option.numeric').hide();
    $('#text-db-type').find('option.text').show();
    $('#text-db-type').val('varchar');
    
    $('#text-label-text').attr('placeholder', 'Text Field');
    $('#text-name').attr('placeholder', 'text-field-name');
    $('#text-id').attr('placeholder', 'text-field-id');
    $('#text-placeholder').attr('placeholder', 'Text Field Placeholder');
    $('#text-initial-value').attr('placeholder', 'Optional Initial Value');
    
    $('#text-label-text').val('');
    $('#text-name').val('');
    $('#text-id').val('');
    $('#text-placeholder').val('');
    $('#text-initial-value').val('');
    
    $('#text-initial-value').rules('remove', 'email' );
    $('#text-initial-value').rules('remove', 'url' );
    $('#text-initial-value').rules('remove', 'number' );
}

function toTextInput() {
    resetTextForm();
}

function toNumberInput() {
    resetTextForm();
    $('#text-modal-title').html('Number Input');
    $('#text-save-btn').html('Create Number Input');
    
    $('#text-type').val('number');
    
    $('#text-input-form').find('.number-control').slideDown();
    if ( $('#text-spinner').val() === 'none' ) {
        $('#text-input-form').find('.spinner-control').hide();
    } else {
        $('#text-input-form').find('.spinner-control').show();
    }
    
    $('#text-db-type').find('option.numeric').show();
    $('#text-db-type').find('option.text').hide();
    $('#text-db-type').val('int');
    
    $('#text-label-text').attr('placeholder', 'Number Field');
    $('#text-name').attr('placeholder', 'number-field-name');
    $('#text-id').attr('placeholder', 'number-field-id');
    $('#text-placeholder').attr('placeholder', '0');
    $('#text-initial-value').attr('placeholder', 'Optional Initial Value');
    
    $('#text-initial-value').rules('add', { number : true });
}

function toEmailInput() {
    resetTextForm();
    $('#text-type').val('email');
    $('#text-modal-title').html('Email Input');
    $('#text-save-btn').html('Create Email Input');
    
    $('#text-label-text').attr('placeholder', 'Email Field');
    $('#text-name').attr('placeholder', 'email-field-name');
    $('#text-id').attr('placeholder', 'email-field-id');
    $('#text-placeholder').attr('placeholder', 'markangeloangulo@gmail.com');
    $('#text-initial-value').attr('placeholder', 'Optional Initial Value');
    
    $('#text-initial-value').rules('add', { email : true });
}

function toUrlInput() {
    resetTextForm();
    $('#text-type').val('url');
    $('#text-modal-title').html('URL Input');
    $('#text-save-btn').html('Create URL Input');
    
    $('#text-label-text').attr('placeholder', 'URL Field');
    $('#text-name').attr('placeholder', 'url-field-name');
    $('#text-id').attr('placeholder', 'url-field-id');
    $('#text-placeholder').attr('placeholder', 'http://gelo.com');
    $('#text-initial-value').attr('placeholder', 'Optional Initial Value');
    
    $('#text-initial-value').rules('add', { url : true });
}

function toPasswordInput() {
    resetTextForm();
    $('#text-type').val('password');
    $('#text-modal-title').html('Password Input');
    $('#text-save-btn').html('Create Password Input');
    $('#text-input-form').find('.password-control').slideDown();
    
    $('#text-label-text').attr('placeholder', 'Password Field');
    $('#text-name').attr('placeholder', 'password-field-name');
    $('#text-id').attr('placeholder', 'password-field-id');
    $('#text-placeholder').attr('placeholder', 's4mpl3P4ssw0rd');
    $('#text-initial-value').attr('placeholder', 'Optional Initial Value');
}

$(function() {
    
    var icons = {
        'text'              : '<i class="fa fa-edit"></i>',
        'number'            : '#',
        'email'             : '<i class="fa fa-envelope"></i>',
        'url'               : '<i class="fa fa-globe"></i>',
        'password'          : '<i class="fa fa-lock"></i>',
        'confirm-password'  : '<i class="fa fa-unlock"></i>',
        'color'             : '<i class="fa fa-tint"></i>',
        'location'          : '<i class="fa fa-edit"></i>',
        'longitude'         : '<i class="fa fa-pushpin"></i>',
        'latitude'          : '<i class="fa fa-pushpin"></i>'
    };

    // validation rules
    var rules = {};
    rules['label']                          = set_rules('label', 'label', 'required|maxlength[6]');
    rules['label-text']                     = set_rules('label-text', 'label-text', 'required|maxlength[25]');
    rules['bold-label']                     = set_rules('bold-label', 'bold-label', 'maxlength[25]');
    rules['name']                           = set_rules('name', 'name', 'required|maxlength[50]');
    rules['id']                             = set_rules('id', 'id', 'required|maxlength[50]');
    rules['placeholder']                    = set_rules('placeholder', 'placeholder', 'maxlength[50]');
    rules['initial-value']                  = set_rules('initial-value', 'initial-value', 'maxlength[255]');
    rules['type']                           = set_rules('type', 'type', 'maxlength[25]');
    rules['spinner']                        = set_rules('spinner', 'spinner', 'required|maxlength[25]');
    rules['spinner-step']                   = set_rules('spinner-step', 'spinner-step', 'numeric|maxlength[11]');
    rules['confirm-password']               = set_rules('confirm-password', 'confirm-password', 'maxlength[25]');
    rules['db-type']                        = set_rules('db-type', 'db-type', 'required|maxlength[25]');
    rules['min-length']                     = set_rules('min-length', 'min-length', 'numeric|maxlength[11]');
    rules['max-length']                     = set_rules('max-length', 'max-length', 'required|numeric|maxlength[11]');
    rules['show-list']                      = set_rules('show-list', 'show-list', 'maxlength[25]');
    rules['searchable']                     = set_rules('searchable', 'searchable', 'maxlength[25]');
    rules['show-api']                       = set_rules('show-api', 'show-api', 'maxlength[25]');
    rules['icon']                           = set_rules('icon', 'icon', 'required|maxlength[50]');
    rules['change-icon']                    = set_rules('change-icon', 'change-icon', 'maxlength[50]');
    rules['guideline']                      = set_rules('guideline', 'guideline', 'required|maxlength[50]');
    rules['guideline-title']                = set_rules('guideline-title', 'guideline-title', 'required|maxlength[50]');
    rules['guideline-text']                 = set_rules('guideline-text', 'guideline-text', 'required|maxlength[255]');
    rules['horizontal-size']                = set_rules('horizontal-size', 'horizontal-size', 'required|maxlength[25]');
    rules['position']                       = set_rules('position', 'position', 'required|maxlength[25]');

    // fieldset form validation
    $("#text-input-form").validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
    
    resetTextForm();
    
    // show/hide label controls
    $('#text-label').change(function() {
        if( $(this).val() === 'none' ) {
            $('#text-input-form').find('.label-control').slideUp();
        } else {
            $('#text-input-form').find('.label-control').slideDown();
        }
    });
    
    // show/hide spinner controls
    $('#text-spinner').change(function() {
        if( $(this).val() === 'none' ) {
            $('#text-input-form').find('.spinner-control').slideUp();
        } else {
            $('#text-input-form').find('.spinner-control').slideDown();
        }
    });
    
    // auto fill-up text name, id and placeholder using label text
    $('#text-label-text').change(function() {
        var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
        ( $('#text-name').val() === '' || $('#text-name').val() === undefined ) ? $('#text-name').val(textLabel) : '';
        ( $('#text-id').val() === '' || $('#text-id').val() === undefined ) ? $('#text-id').val(textLabel) : '';
        ( $('#text-placeholder').val() === '' || $('#text-placeholder').val() === undefined ) ? $('#text-placeholder').val( $(this).val() ) : '';
    });
    
    // auto fill-up text name, id and placeholder using label name
    $('#text-name').change(function() {
        if( $('#text-label').val() === 'none' ) {
            var textLabel = $(this).val().toLowerCase().replace(/ /g,'-');
            ( $('#text-id').val() === '' || $('#text-id').val() === undefined ) ? $('#text-id').val(textLabel) : '';
            ( $('#text-placeholder').val() === '' || $('#text-placeholder').val() === undefined ) ? $('#text-placeholder').val( $(this).val() ) : '';
        }
    });
    
    // show/hide icon controls
    $('#text-icon').change(function() {
        if( $(this).val() === 'none' ) {
            $('#text-input-form').find('.icon-control').slideUp();
        } else {
            $('#text-input-form').find('.icon-control').slideDown();
        }
    });
    
    // show/hide guideline controls
    $('#text-guideline').change(function() {
        if( $(this).val() === 'none' ) {
            $('#text-input-form').find('.guideline-control').slideUp();
        } else if(  $(this).val() === 'label' ) {
            $('#text-input-form').find('.guideline-control').slideDown();
            $('#text-guideline-title-container').slideUp();
        } else {
            $('#text-input-form').find('.guideline-control').slideDown();
        }
    });
    
    // show/hide controls
    $('#text-type').change(function() {
        if( $(this).val() === 'text' ) {
            toTextInput();
        }
        if( $(this).val() === 'number' ) {
            toNumberInput();
        }
        if( $(this).val() === 'email' ) {
            toEmailInput();
        }
        if( $(this).val() === 'url' ) {
            toUrlInput();
        }
        if( $(this).val() === 'password' ) {
            toPasswordInput();
        }
    });
    
    $('#text-save-btn').click(function(event) {
        event.preventDefault();
        $('#text-input-form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#text-input-form').valid()) {

            var values                  = $('#text-input-form').serializeJSON();
            
            // label
            var label                   = ( values['label'] !== undefined && values['label'] !== '' ) ? values['label'] : '';
            var labelPosition           = ( label !== '' || label !== 'none' ) ? ' align-' + label : 'none';
            var labelText               = ( values['label-text'] !== undefined && values['label-text'] !== '' ) ? values['label-text'] : '';
            
            // field data
            var fieldName               = ( values['name'] !== undefined && values['name'] !== '' ) ? values['name'] : '';
            var fieldId                 = ( values['id'] !== undefined && values['id'] !== '' ) ? values['id'] : '';
            var placeholder             = ( values['placeholder'] !== undefined && values['placeholder'] !== '' ) ? ' placeholder="' +values['placeholder']+ '"' : '';
            var initialValue            = ( values['initial-value'] !== undefined && values['initial-value'] !== '' ) ? ' value="' + values['initial-value'] + '"' : '';
            var type                    = ( values['type'] !== undefined && values['type'] !== '' ) ? values['type'] : '';
            
            // min and max length
            var minLength               = ( values['min-length'] !== undefined && values['min-length'] !== '') ? ' minlength="' + values['min-length'] + '"' : '';
            var maxLength               = ( values['max-length'] !== undefined && values['max-length'] !== '' ) ? ' maxlength="' + values['max-length'] + '"' : '';
            
            // guideline
            var guideline               = ( values['guideline'] !== undefined && values['guideline'] !== '' ) ? values['guideline'] : '';
            var guidelineTitle          = ( values['guideline-title'] !== undefined && values['guideline-title'] !== '' ) ? values['guideline-title'] : '';
            var guidelineText           = ( values['guideline-text'] !== undefined && values['guideline-text'] !== '' ) ? values['guideline-text'] : '';
            
            // size and position
            var horizontalSize          = ( values['horizontal-size'] !== undefined && values['horizontal-size'] !== '' ) ? ' ' + values['horizontal-size'] : '';
            var verticalSize            = ( values['vertical-size'] !== undefined && values['vertical-size'] !== '' )? ' ' + values['vertical-size'] : '';
            var position                = ( values['position'] !== undefined && values['position'] !== '' ) ? ' ' + values['position'] : '';
            
            // type
            var email                   = ( type === 'email' ) ? ' email="true"' : '';
            var url                     = ( type === 'url' ) ? ' url="true"' : '';
            var password                = ( type === 'password' ) ? 'password' : 'text';
            
            // validations
            var validations             = values['validations'];
            var required                = $.inArray('required', validations) !== -1 ? ' required="true" ' : ' ';
            var requiredLabel           = ( $.inArray('required', validations) !== -1 && values['label'] !== '' && values['label'] !== 'none') ? ' *' : '';
            
            // icon
            var hasIcon                 = ( values['icon'] !== undefined &&  values['icon'] !== '' && values['icon'] !== 'none' ) ? true : false;
            var icon                    = ( values['icon'] !== undefined && values['icon'] !== '' ) ? values['icon'] : 'none';
            var changeIcon              = ( values['change-icon'] !== undefined && values['change-icon'] !== '' ) ? values['change-icon'] : icons[type];

            // spinner
            var useSpinner = ( values['spinner'] !== undefined && values['spinner'] !== '' && values['spinner'] !== 'none' ) ? true : false;
            var spinnerPosition = ( values['spinner'] !== undefined && values['spinner'] !== '' && values['spinner'] !== 'none' ) ? values['spinner'] : 'right';
            spinnerPosition = spinnerPosition.replace(/horizontal-/, '');
            spinnerPosition = spinnerPosition.replace(/vertical-/, ''); 
            var orientation = ( values['spinner'].indexOf('horizontal') !== -1 ) ? 'horizontal' : 'vertical'; 
            var step = ( values['spinner-step'] !== undefined && values['spinner-step'] !== '' ) ? parseFloat( values['spinner-step'] ) : 1;
            
            var markup = '';
            var list = $('<li class="form-group row"></li>');
            markup += '<button type="button" class="close" aria-hidden="true">&times;</button>\n';
            markup += '<label for="' +fieldId+ '" class="control-label' +labelPosition+ ' col-3">\n';
            markup += labelText + requiredLabel + '\n';
            markup += '<br><small>' +guidelineText+ '</small>\n';
            markup += '</label>\n';
            markup += '<div class="control-group col-9">\n';
            markup += '<div class="input-size' + horizontalSize + position + '">\n';
            
            if( hasIcon ) {
                markup += '<div class="input-group">';
            }
            if( hasIcon && ( icon === 'left' || icon === 'both' ) ) {
                markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
            }  
            markup += '<input type="' +password+ '" name="' +fieldName+ '" id="' +fieldId+ '" class="form-control' + verticalSize + '"' + placeholder + email + url + initialValue + required + minLength + maxLength + '>\n';
            if( hasIcon && ( icon === 'right' || icon === 'both' ) ) {
                markup += '<span class="input-group-addon">' +changeIcon+ '</span>';
            }

            if( hasIcon ) {
                markup += '</div>';
            }
            markup += '</div>\n';
            markup += '</div>\n';
            
            list.html(markup);
            list.data('controls', values);
            
            $('#form-sortable li:first-child fieldset:first-child ul').prepend(list);
            
            // spinner
            if( type === 'number' && useSpinner ) {
                $('#' + fieldId).btSpinner({
                    'step' : step,
                    'position' : spinnerPosition,
                    'orientation': orientation
                });
            }
            
//            alert(values.toSource());
            $('#text-input-modal').modal('hide');








//            var values = $('#text_input_form').serializeJSON();
//            var list = $('<li>');
//
//            // field data
//            var type = values['type'];
//            var label = values['label'];
//            var field_name = values['name'];
//            var field_id = values['id'];
//            var placeholder = values['placeholder'] !== undefined ? values['placeholder'] : '';
//            var initial_value = values['initial_value'] !== undefined ? ' value="' + values['initial_value'] +'"' : '';
//            var min_length = values['min_length'];
//            var max_length = values['max_length'];
//            
//            // password
//            var field_type = type === 'password' ? 'password' : 'text';
//            var confirm_password = (values['confirm_password'] !== undefined && values['confirm_password'] !== '') ? true : false;
//            
//            // validations
//            var validations = values['validations'];
//            var required = $.inArray('required', validations) !== -1 ? ' data-rule-required="true" ' : ' ';
//            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
//            var valid_number = $.inArray('numeric', validations) !== -1 ? ' data-rule-number="true"="true" ' : ' ';
//            var valid_email = $.inArray('valid_email', validations) !== -1 ? ' data-rule-email="true" ' : ' ';
//            var valid_url = $.inArray('valid_url', validations) !== -1 ? ' data-rule-url="true" ' : ' ';
//
//            // icons
//            var icon = (values['icon'] !== undefined && values['icon'] !== '') ? true : false;
//            var change_icon = (values['change_icon'] !== undefined && values['change_icon'] !== '') ? values['change_icon'] : icons[type];
//            
//            // spinner
//            var spinner = (values['spinner'] !== undefined && values['spinner'] !== '') ? ' spinner' : '';
//            var use_spinner = (values['spinner'] !== undefined && values['spinner'] !== '') ? true : false;
//            var spinner_value = values['spinner'];
//            
//            // guidelines
//            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
//            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
//            
//            
//            // html markup
//            var markup = '';
//            markup += '<div class="control-group">';
//            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
//            
//            if(guideline) {
//                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
//            } else {
//                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label+ '</label>';
//            }
//
//            markup += '<div class="controls">';
//            if(icon && ! use_spinner) {
//                markup += '<div class="input-prepend"><span class="add-on">' +change_icon+ '</span>';
//            }
//            markup += '<input type="' +field_type+ '" name="' +field_name+ '" id="' +field_id+ '" class="input-xlarge' +spinner+ '"' +required+ 'data-rule-minlength="' +min_length+ '" data-rule-maxlenght="' +max_length+ '"' + valid_email + valid_url + valid_number + 'placeholder="' +placeholder+ '"' +initial_value+ '>';
//            if(icon && ! use_spinner) {
//                markup += '</div>';
//            }
//            markup += '</div></div>';
//            
//            if(field_type === 'password' && confirm_password) {
//
//                markup += '<div class="control-group">';
//                if(guideline) {
//                    markup += '<label for="confirm_' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="Retype ' +field_name+ '">Confirm ' +label+ required_label+ '</label>';
//                } else {
//                    markup += '<label for="confirm_' +field_id+ '" class="control-label handle">Confirm ' +label+ required_label+ '</label>';
//                }
//                markup += '<div class="controls">';
//                if(icon) {
//                    markup += '<div class="input-prepend"><span class="add-on"><i class="icon-unlock"></i></span>';
//                }
//                markup += '<input type="' +field_type+ '" name="confirm_' +field_name+ '" id="confirm_' +field_id+ '" class="input-xlarge"' +required+ 'data-rule-minlength="' +min_length+ '" data-rule-maxlenght="' +max_length+ '" data-rule-equalto="' +field_id+ '" placeholder="Confirm ' +placeholder+ '" value="">';
//                if(icon) {
//                    markup += '</div>';
//                }
//                markup += '</div></div>';
//            }
//            
//            // attach object to dom
//            list.html(markup);
//            list.data('controls', values);
//            $('ul#sortable').append(list);
//            
//            // reinitialize popovers
//            $('body').popover(popover_options);
//            
//            if(use_spinner) {
//                $('ul#sortable li:last-child .spinner').spinner({step: spinner_value});
//            }
//
//            // hide modal
//            $('#text_input_modal').modal('hide');
        }
        
        // submit form for validation purposes
        $('#text-input-form').submit();
    });
    
    // generic text button
    $('#generic-text-btn').click(function() {
        resetTextForm();
        $('#text-type-container').show();
        $('#text-input-modal').modal({
            width: '95%'
        });
    });
    
    // text button
    $('#text-btn').click(function() {
        resetTextForm();
        $('#text-type-container').hide();
        $('#text-input-modal').modal({
            width: '95%'
        });
    });
    
    // number button
    $('#number-btn').click(function() {
        resetTextForm();
        toNumberInput();
        $('#text-type-container').hide();
        $('#text-input-modal').modal({
            width: '95%'
        });
    });
    
    // email button
    $('#email-btn').click(function() {
        resetTextForm();
        toEmailInput();
        $('#text-type-container').hide();
        $('#text-input-modal').modal({
            width: '95%'
        });
    });
    
    // url button
    $('#url-btn').click(function() {
        resetTextForm();
        toUrlInput();
        $('#text-type-container').hide();
        $('#text-input-modal').modal({
            width: '95%'
        });
    });
    
    // password button
    $('#password-btn').click(function() {
        resetTextForm();
        toPasswordInput();
        $('#text-type-container').hide();
        $('#text-input-modal').modal({
            width: '95%'
        });
    });
    
});

